package com.ehome.emergency.controller.admin;

import com.ehome.emergency.common.ApiPath;
import com.ehome.emergency.entities.LoginPage;
import com.ehome.emergency.enums.Status;
import com.ehome.emergency.service.ILoginPageService;
import com.ehome.emergency.utils.ApplicationPropertiesUtils;
import com.ehome.emergency.utils.Pager;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * BasicFramework
 *
 * @author: haoxiaolei
 * @date: 2016-07-18 10:40
 * @desc: 登录页设置
 */
@Controller
public class LoginPageController extends BaseAdminController {
    private static final Logger LOG = LoggerFactory.getLogger(LoginPageController.class);

    @Resource
    private ILoginPageService loginPageService;

    @RequestMapping(value = ApiPath.ADMIN_LOGINPAGE_ENTRY)
    public String entry() {
        return "admin/system/login_page_list";
    }

    @RequestMapping(value = ApiPath.ADMIN_LOGINPAGE_LIST, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> list(Pager pager) {
        LOG.info("登录页设置管理列表页面");
        Map<String, Object> resultMap = new HashMap<>();
        DetachedCriteria criteria = DetachedCriteria.forClass(LoginPage.class);
        try {
            List<LoginPage> loginPageList = loginPageService.findListPager(LoginPage.class, criteria, pager);
            resultMap.put(STATUS, SUCCESS);
            resultMap.put(ROWS, loginPageList);
            resultMap.put(TOTAL, pager.getTotalRecords());
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return resultMap;
    }

    @RequestMapping(value = ApiPath.ADMIN_LOGINPAGE_ADD)
    public String add() {
        LOG.info("登录页设置管理添加页面");
        return "admin/system/login_page_input";
    }

    @RequestMapping(value = ApiPath.ADMIN_LOGINPAGE_SAVE, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> save(@RequestParam(value = "backgroundImage", required = false) MultipartFile file, HttpServletRequest request) {
        LOG.info("登录页设置管理保存");
        Map<String, Object> resultMap = new HashMap<>();
        String fileName = "";
        if (file != null) {
            // 存到webapp目录下的某个文件夹
            String path = System.getProperty("webapp.root") + ApplicationPropertiesUtils.getValue("upload.path");
            fileName = file.getOriginalFilename();
            File targetFile = new File(path, fileName);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            try {
                file.transferTo(targetFile);
            } catch (IOException e) {
                resultMap.put(STATUS, ERROR);
                resultMap.put(MSG, "上传图片失败，请联系管理员！");
                LOG.error(e.getMessage(), e);
                return resultMap;
            }
        }
        String tenantId = (String) request.getSession().getAttribute(TENANT_ID);
        LoginPage loginPage = new LoginPage();
        loginPage.setBackgroundImage(fileName);
        loginPage.setBackgroundColor(getParameter(request, "backgroundColor"));
        loginPage.setDescription(getParameter(request, "description"));
        loginPage.setStatus(Status.AVAILABLE.name());
        loginPage.setTenantId(tenantId);
        try {
            loginPageService.save(loginPage);
            resultMap.put(STATUS, SUCCESS);
            resultMap.put(MSG, "保存成功");
        } catch (Exception e) {
            resultMap.put(STATUS, ERROR);
            resultMap.put(MSG, "保存失败，请联系管理员！");
            LOG.error(e.getMessage(), e);
        }
        return resultMap;
    }

    @RequestMapping(value = ApiPath.ADMIN_LOGINPAGE_EDIT)
    public String edit(String id, Model model) {
        LOG.info("登录页设置修改页面");
        try {
            LoginPage loginPage = loginPageService.findById(LoginPage.class, id);
            model.addAttribute("loginPage", loginPage);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        model.addAttribute("loginPageId", id);
        return "admin/system/login_page_input";
    }

    @RequestMapping(value = ApiPath.ADMIN_LOGINPAGE_REMOVE, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> remove(String ids) {
        LOG.info("登录页设置管理删除操作");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (StringUtils.isNotBlank(ids)) {
                List<Long> idList = new ArrayList<>();
                String[] idArray = ids.split(",");
                for (String tid : idArray) {
                    idList.add(Long.valueOf(tid));
                }
                DetachedCriteria criteria = DetachedCriteria.forClass(LoginPage.class);
                criteria.add(Restrictions.in("id", idList));
                loginPageService.delete(LoginPage.class, criteria);
                resultMap.put(STATUS, SUCCESS);
                resultMap.put(MSG, "删除成功");
            }
        } catch (Exception e) {
            resultMap.put(STATUS, ERROR);
            resultMap.put(MSG, "删除失败，请联系管理员！");
            LOG.error(e.getMessage(), e);
        }
        return resultMap;
    }

    @RequestMapping(value = ApiPath.ADMIN_LOGINPAGE_ENABLE, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> enable(String ids, HttpServletRequest request) {
        LOG.info("登录页设置启用");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (StringUtils.isNotBlank(ids)) {
                changeStatus(ids, Status.AVAILABLE, request);
                resultMap.put(STATUS, SUCCESS);
                resultMap.put(MSG, "启用成功");
            }
        } catch (Exception e) {
            resultMap.put(STATUS, ERROR);
            resultMap.put(MSG, "启用失败，请联系管理员！");
            LOG.error(e.getMessage(), e);
        }
        return resultMap;
    }

    @RequestMapping(value = ApiPath.ADMIN_LOGINPAGE_DISABLE, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> disable(String ids, HttpServletRequest request) {
        LOG.info("登录页设置禁用");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (StringUtils.isNotBlank(ids)) {
                changeStatus(ids, Status.UNAVAILABLE, request);
                resultMap.put(STATUS, SUCCESS);
                resultMap.put(MSG, "禁用成功");
            }
        } catch (Exception e) {
            resultMap.put(STATUS, ERROR);
            resultMap.put(MSG, "禁用失败，请联系管理员！");
            LOG.error(e.getMessage(), e);
        }
        return resultMap;
    }


    /**
     * 改变状态
     * @param ids    主键ids，以逗号分隔
     * @param status 状态
     */
    private void changeStatus(String ids, Status status, HttpServletRequest request) throws Exception {
        List idList = new ArrayList<>();
        String[] midArray = ids.split(",");
        for (String mid : midArray) {
            idList.add(Long.valueOf(mid));
        }
        String tenantId = request.getSession().getAttribute(TENANT_ID).toString();
        DetachedCriteria criteria = DetachedCriteria.forClass(LoginPage.class);
        criteria.add(Restrictions.in("id", idList));
        criteria.add(Restrictions.eq("tenantId", tenantId));
        List<LoginPage> loginPageList = loginPageService.findList(LoginPage.class, criteria);
        if (loginPageList != null && loginPageList.size() > 0) {
            for (LoginPage loginPage : loginPageList) {
                loginPage.setStatus(status.name());
            }
        }
        loginPageService.update(loginPageList);
    }








}
